import React, {Component,} from "react";
// import {connect}
import Admin from "../../../layout/Admin";
import {
    PageHeader,
    Table,
    Divider,
    Form,
    Modal,
    Input,
    Upload,
    Button,
    Progress,
    Popconfirm,
    Popover, Radio,
} from "antd";
import {DownOutlined, UploadOutlined, LeftOutlined, RightOutlined, } from '@ant-design/icons'

import VideoModel from "../../../model/video";

class Video extends Component {

    constructor(props) {
        super(props)
        this.videoModel = new VideoModel()
        this.state = {
            // 列表
            p: 0,
            videoList: [],
            // form
            initialValues: {
                src: '',
                title: '',
            },
            video: [],
            titleimg: [],
            uploadProgress: 0,
            uploadSucc: false,
            heng: 0,
            // modals
            modal: {
                // video: false,
                upload: false,
            },
        }
    }

    componentDidMount() {

        this.all()

    }

    all = () => {
        this.videoModel.all({p: this.state.p,}).then(data => {
            const videoList = data.data.ok.data
            videoList.forEach(v => v.preview = false)
            this.setState({
                videoList,
            })
        })
    }

    fetchPage = (p) => {

        this.setState({
            p,
        }, () => {
            this.all()
        })

    }

    prevPage = () => {

        const p = this.state.p - 1
        this.fetchPage(p)

    }


    nextPage = () => {

        const p = this.state.p + 1
        this.fetchPage(p)

    }

    // modalAction

    modalShow = (key) => {
        this.setState({
            modal: {
                [key]: true
            },
        })
    }

    modalCancel = () => {
        this.setState({
            modal: false,
        })
    }

    onRadioChange = e => {
        this.setState({
            heng: e.target.value,
        })
    };

    renderImgCol = (url) => {
        const content = <img src={url} alt=''/>
        return (
            <Popover
                content={content}
                title="图片详情"
                trigger="click"
            >
                <img src={url} alt='' style={{width: '50px'}}/>
            </Popover>
        )
    }

    renderVideoCol = (url, data, index,) => {
        const content = <video src={url} autoPlay={false} controls/>

        return (
            <Popover
                content={content}
                title="视频详情"
                trigger="click"
            >
                <Button type="primary">视频详情</Button>
            </Popover>
        )
    }

    onUploadFinish = values => {
        let video = this.state.video[0]
        let titleimg = this.state.titleimg[0]
        let params = {
            ...values,
            video,
            titleimg,
            heng: this.state.heng,
        }
        let v = this.videoModel
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data',
                // 'Access-Control-Allow-Origin': '*',
            },
            // 'Content-Type': 'multipart/form-data',
            onUploadProgress: (progressEvent) => {

                // 使用本地 progress 事件
                if (progressEvent.lengthComputable) {

                    let num = Math.round((progressEvent.loaded / progressEvent.total) * 100)
                    // this.process = num // 使用某种 UI 进度条组件会用到的百分比
                    this.setState({
                        uploadProgress: num,
                    })
                }
            }
        }
        v.add(params, config)
            .then((resp) => {
                const data = resp.data
                if (data.err) {
                    this.setState({
                        uploadSucc: false,
                    })
                } else {
                    this.setState({
                        uploadSucc: true,
                    })
                }
            })
            .then(() => {
                this.form.resetFields()
                this.setState({
                    video: [],
                    titleimg: [],
                    uploadProgress: 0,
                })
            })
            .then(() => {
                return v.all({p: 0,})
            })
            .then(data => {
                const videoList = data.data.ok.data
                this.setState({
                    videoList,
                })
            })
    }

    onUploadFinishFailed = errorInfo => {
        console.log('Failed:', errorInfo)
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {
            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    };
                });
            },
            beforeUpload: file => {
                this.setState(state => ({
                    [name]: [...state[name], file],
                }));
                return false;
            },

            fileList,
            // state[name],
        }

    }

    deleteVideo = video => {
        let params = {id: video.Id,}
        const vm = this.videoModel
        vm.delete(params)
            .then(() => {
                return vm.all({p: 0,})
            })
            .then(data => {
                const videoList = data.data.ok.data
                this.setState({
                    videoList,
                })
            })
    }

    render() {

        const header = <div style={{background: '#fff'}}>
            <PageHeader title='视频管理'/>
        </div>

        const initialValues = this.state.initialValues
        let status = 'active'
        let succ = this.state.uploadSucc
        let percent = this.state.uploadProgress
        if (percent === 100 && succ) {
            status = ''
        }
        if (percent === 100 && !succ) {
            status = 'exception'
        }

        const uploadForm = <Form
            ref={el => this.form = el}
            name='addgamevideo'
            initialValues={initialValues}
            onFinish={this.onUploadFinish}
            onFinishFailed={this.onUploadFinishFailed}
        >
            <Form.Item
                label="来源"
                name="src"
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="标题"
                name="title"
            >
                <Input />
            </Form.Item>

            <Form.Item
                // name="video"
                label="视频"
            >
                <Upload {...this.uploadInputProps('video')}>
                    <Button>
                        <UploadOutlined  /> Click to upload
                    </Button>
                </Upload>
            </Form.Item>

            <Form.Item
                // name="titleimg"
                label="缩略图"

            >
                <Upload {...this.uploadInputProps('titleimg')}>
                    <Button>
                        <UploadOutlined  /> Click to upload
                    </Button>
                </Upload>
            </Form.Item>

            <Radio.Group onChange={this.onRadioChange} value={this.state.heng}>
                <Radio value={0}>竖屏</Radio>
                <Radio value={1}>横屏</Radio>
            </Radio.Group>

            <Progress percent={percent} status={status} />
            <Divider />

            <Form.Item>

                <Button htmlType="button" onClick={e => this.modalCancel('video')}>
                    取消
                </Button>

                <Button type="primary" htmlType="submit" style={{marginLeft: 8}}>
                    Submit
                </Button>


            </Form.Item>
        </Form>


        const uploadModal = <Modal
            title="上传视频"
            visible={this.state.modal.upload}
            footer={null}
            maskClosable={true}
            onCancel={() => this.modalCancel('upload')}
        >
            {uploadForm}
        </Modal>


        const columns = [
            {
                title: 'Id',
                dataIndex: 'Id',
                render: Id => <span>{Id}</span>,
            },
            {
                title: 'Title',
                dataIndex: 'Title',
                render: Title => <span>{Title}</span>,
            },
            {
                title: 'Src',
                dataIndex: 'Src',
                render: Src => <span>{Src}</span>,
            },
            {
                title: 'Titleimg',
                dataIndex: 'Titleimg',
                // render: Titleimg => <img src={Titleimg} alt='' style={{width: '50px'}}/>,
                render: (text) => this.renderImgCol(text)
                // render: Titleimg => <img src={Titleimg} alt='' style={{width: '50px'}}/>,
            },
            {
                title: 'Url',
                dataIndex: 'Url',
                render: (text, record, index) => this.renderVideoCol(text, record, index),
            },
            {
                title: 'Createt',
                dataIndex: 'Createt',
                render: Createt => <span>{Createt.slice(0, 16)}</span>,
            },

            {
                title: '横竖屏',
                dataIndex: 'Heng',
                render: heng => <span>{heng ? '横屏' : '竖屏'}</span>,
            },

            {
                title: '操作',
                dataIndex: '操作',
                render: (text, record) => (
                    <Popconfirm title="确定删除?" onConfirm={(e) => this.deleteVideo(record)}>
                        <a>Delete</a>
                    </Popconfirm >
                ),
            },
        ]

        const footer = <div style={{
            paddingTop: 8,
            display: "flex",
            justifyContent: "flex-end",
        }}>
            <Button
                style={{marginRight: 8,}}
                onClick={(e) => this.prevPage()}
            ><LeftOutlined /></Button>
            <a className='ant-pagination-item ant-pagination-item-active '>{this.state.p + 1}</a>
            <Button
                onClick={(e) => this.nextPage()}
            ><RightOutlined /></Button>
        </div>

        const table = <div className='list-container'>

            <div style={{marginBottom: '16px',}}>
                <Button onClick={() => this.modalShow('upload')}>添加视频</Button>
            </div>

            <Table
                dataSource={this.state.videoList}
                columns={columns}
                rowKey={(record, index) => index}
                pagination={false}
            />
            {footer}

        </div>

        return <>
            {uploadModal}
            <Admin>
                {header}
                {table}
            </Admin>
        </>
    }


}

export default Video
